﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using Newtonsoft.Json;
using System.Threading;
using System.Net;
using System.IO;

namespace __moov
{
    public partial class frmMain : Form
    {
        // This block is used to animate the window
        public const int AW_ACTIVATE = 0x20000;
        public const int AW_HIDE = 0x10000;
        public const int AW_BLEND = 0x80000;
        public const int AW_CENTER = 0x00000010;
        public const int AW_SLIDE = 0X40000;
        public const int AW_HOR_POSITIVE = 0x1;
        public const int AW_HOR_NEGATIVE = 0X2;
        public const int AW_VER_POSITIVE = 0x00000004;
        public const int AW_VER_NEGATIVE = 0x00000008;

        public const string defaultSearchText = "--- Search Contacts Here ---";
        public bool _stopWorker = false;
        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        public static extern int AnimateWindow(IntPtr hwand, int dwTime, int dwFlags);
        // -------------------------------------------------------//
       
        public frmMain()
        {
            InitializeComponent();
            this.SetDesktopLocation(Screen.PrimaryScreen.WorkingArea.Right - this.Width,
                    Screen.PrimaryScreen.WorkingArea.Bottom - this.Height);

            //Fix stacking order for some controls
            pContactControls.Controls[btnSearchContact.Name].BringToFront();
            pContactControls.Controls[btnBlockContact.Name].BringToFront();
            this.Refresh();
            
        }

        private void envFrmLoad(object sender, EventArgs e)
        {
            //Performs window animation
            AnimateWindow(this.Handle, 500, AW_ACTIVATE | AW_SLIDE | AW_VER_NEGATIVE);

            // TODO: This line of code loads data into the 'moovDataSet.tblContacts' table. You can move, or remove it, as needed.
            this.tblContactsTableAdapter.Fill(this.moovDataSet.tblContacts);

            //Thread worker = new Thread(doWork);
            //worker.Start();     


            //Fix stacking order for some controls
            pContactControls.Controls[btnSearchContact.Name].BringToFront();
            pContactControls.Controls[btnBlockContact.Name].BringToFront();
            this.Refresh();
       }

        private void envBtnCloseClick(object sender, EventArgs e)
        {
            AnimateWindow(this.Handle, 500, AW_ACTIVATE | AW_SLIDE | AW_VER_POSITIVE | AW_HIDE);
            this.Close();
        }

        private void envBtnSettingClick(object sender, EventArgs e)
        {
            //display the settings form
            //FrmSettings frmSettings = new FrmSettings();
            //frmSettings.ShowDialog();
            frmWelcome frm_welcome = new frmWelcome();
            frm_welcome.Show();
        }

        private void envTxtSearchGainFocus(object sender, EventArgs e)
        {
            txtSearch.Clear();
        }

        private void envTxtSearchLooseFocus(object sender, EventArgs e)
        {
            txtSearch.Text = defaultSearchText;

        }

        private void envTxtSearchTextChanged(object sender, EventArgs e)
        {
            if (txtSearch.Text == defaultSearchText) return;
            this.tblContactsTableAdapter.FillByName(this.moovDataSet.tblContacts, txtSearch.Text);            
        }

        

        private void btn_send_Click(object sender, EventArgs e)
        {

        }

        private void doWork()
        {
            while (!_stopWorker)
            {
                //Prepare to pull contacts
                String[] url = new String[3];
                url[0] = Properties.Settings.Default.requestPartialURL;
                url[1] = Properties.Settings.Default.userId;
                url[2] = "countries";

                String[] urlParam = new String[3];
                urlParam[0] = "fields=id,name";
                urlParam[1] = "status=A";
                urlParam[2] = "fmt=json";

                try
                {
                    String uri = String.Join("/", url) + "?" + String.Join("&", urlParam);
                    WebRequest webRequest = WebRequest.Create(uri);
                    webRequest.Method = "GET";
                    WebResponse webResponse = webRequest.GetResponse();
                    //WebHeaderCollection responseHeader = (WebHeaderCollection) webResponse.Headers.GetEnumerator();
                    //foreach(string key in webResponse.Headers.AllKeys)
                    //{
                    //    MessageBox.Show(key);
                    //}
                    //while (responseHeader.)
                    //{
                    StreamReader responseReader = new StreamReader(webResponse.GetResponseStream());
                    string str = null;
                    while ((str = responseReader.ReadLine()) != null)
                    {
                        bool contactExist = false;
                        ContactsPOCO[] apiContactsResponse = JsonConvert.DeserializeObject<ContactsPOCO[]>(str);
                        foreach (ContactsPOCO requestedContact in apiContactsResponse)
                        {
                            //ContactsCOJO[] existingContact = this.tblContactsTableAdapter.GetData().ToArray<ContactsCOJO>();
                            //check existing data against new ones
                            foreach (DataRow existingContact in this.tblContactsTableAdapter.GetData().Rows)
                            {
                                if (requestedContact.id == ((string)existingContact.ItemArray[0]))
                                {
                                    contactExist = true;
                                    break;
                                }
                            }

                            //if (!contactExist) this.tblContactsTableAdapter.Insert("testName", "testMsisdn", "testEmail");
                            //contactExist = false;
                        }
                    }
                    //}

                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.ToString());
                }

                Thread.Sleep(10000);
            }
        }

        private void btnSearchContactClick(object sender, EventArgs e)
        {

        }

        private void btnBlockContactClick(object sender, EventArgs e)
        {

        }

    }
}
